<!doctype html>
<meta charset="utf-8">
<title>登录 / 借阅系统</title>
<style>
  body{font-family:Arial,Helvetica,sans-serif;font-size:14px}
  table{border-collapse:collapse;margin-top:6px}
  td,th{border:1px solid #999;padding:4px 8px}
  button{margin:0 2px;padding:2px 6px}
  .hide{display:none}
  input[type=text],input[type=number]{width:120px;margin-right:4px}
</style>


<form id="f">
  <input name="u" placeholder="用户名" required>
  <input name="p" type="password" placeholder="密码" required>
  <button type="submit" id="btn">登录</button>
</form>
<a href="#" id="toggle">切换注册</a>
<div id="info" class="hide">
  欢迎 <span id="username"></span>（ID：<span id="uid"></span>） 权限：<span id="perm"></span>
</div>

<!-- 管理员 -->
<div id="adminPanel" class="hide">
  <h3>管理员操作</h3>
  <div>
    <input id="newTitle" placeholder="书名">
    <input id="newAuthor" placeholder="作者">
    <button onclick="addBook()">添加书籍</button>
  </div>
  <div style="margin-top:4px">
    <input id="updBookId" type="number" placeholder="书籍ID">
    <input id="updStockValue" type="number" placeholder="新库存">
    <button onclick="updStock()">修改库存</button>
  </div>
</div>


<h3>全部书籍</h3>
<table id="bookTable">
  <thead>
    <tr><th>ID</th><th>书名</th><th>作者</th><th>库存</th><th>操作</th></tr>
  </thead>
  <tbody></tbody>
</table>


<h3 id="borrowTitle" class="hide">借阅记录</h3>
<table id="borrowTable" class="hide">
  <thead>
    <tr>
      <th>借阅ID</th><th>书名</th><th>作者</th><th>用户名</th>
      <th>借阅日期</th><th>归还日期</th><th>操作</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

<script>
const base = 'http://192.168.232.129:8080';
const shortDate = str => str ? str.split('T')[0] : '';


async function get(url){return fetch(url).then(r=>r.json())}
async function post(url){return fetch(url,{method:'POST'}).then(r=>r.text())}


let isLogin = 1, curUser = null;


toggle.onclick=()=>{
  isLogin=!isLogin;
  btn.textContent=isLogin?'登录':'注册';
  toggle.textContent=isLogin?'切换注册':'切换登录';
};


f.onsubmit=async e=>{
  e.preventDefault();
  const {u,p}=f;
  if(isLogin){
    const loginTxt=await post(`${base}/users/loginByName/?username=${u.value}&userpassword=${p.value}`);
    if(loginTxt!=='Login successful'){alert(loginTxt);return;}
    curUser=await get(`${base}/users/byName/?username=${u.value}`);
  }else{
    const regTxt=await post(`${base}/users/?username=${u.value}&userpassword=${p.value}&permission=normal`);
    alert(regTxt);
    if(regTxt!=='User registered successfully')return;
    curUser=await get(`${base}/users/byName/?username=${u.value}`);
  }


  username.textContent=curUser.username;
  uid.textContent=curUser.id;
  perm.textContent=curUser.permission;
  info.classList.remove('hide');
  if(curUser.permission==='admin') adminPanel.classList.remove('hide');
  await refreshAll();
  f.reset();
};


async function refreshAll(){
  await loadBooks();
  await loadBorrowRecords();
}


async function loadBooks(){
  const books=await get(`${base}/books/all`);
  const tbody=bookTable.querySelector('tbody');
  tbody.innerHTML='';
  books.forEach(b=>{
    const canBorrow=+b.stock>0;
    tbody.insertAdjacentHTML('beforeend',
      `<tr>
        <td>${b.id}</td><td>${b.title}</td><td>${b.author}</td><td>${b.stock}</td>
        <td>
          ${curUser ? `<button onclick="borrow(${b.id})" ${canBorrow?'':'disabled'}>借书</button>` : ''}
        </td>
      </tr>`);
  });
}


async function loadBorrowRecords(){
  let records;
  if(curUser.permission==='admin'){
    records=await get(`${base}/borrow-records`);
  }else{
    records=await get(`${base}/borrow-records/byUserId/?user_id=${curUser.id}`);
  }
  const tbody=borrowTable.querySelector('tbody');
  tbody.innerHTML='';
  for(const r of records){
    const [book,user]=await Promise.all([
      get(`${base}/books/byId/?id=${r.book_id}`),
      get(`${base}/users/byId/?id=${r.user_id}`)
    ]);
    const canReturn=curUser.permission==='admin' || r.user_id===curUser.id;
    const returned=r.return_date && r.return_date!=='null';
    tbody.insertAdjacentHTML('beforeend',
      `<tr>
        <td>${r.id}</td><td>${book.title}</td><td>${book.author}</td><td>${user.username}</td>
        <td>${shortDate(r.borrow_date)}</td>
        <td>${returned?shortDate(r.return_date):'未归还'}</td>
        <td>
          ${canReturn && !returned
            ? `<button onclick="returnBook(${r.id})">还书</button>` : ''}
        </td>
      </tr>`);
  }
  borrowTitle.classList.remove('hide');
  borrowTable.classList.remove('hide');
}


async function borrow(bookId){
  const txt=await post(`${base}/borrow-records/borrow?user_id=${curUser.id}&book_id=${bookId}`);
  alert(txt);
  await refreshAll();
}


async function returnBook(recordId){
  const txt=await post(`${base}/borrow-records/return?record_id=${recordId}`);
  alert(txt);
  await refreshAll();
}


async function addBook(){
  const title=newTitle.value.trim(),author=newAuthor.value.trim();
  if(!title||!author){alert('请输入书名和作者');return;}
  const txt=await post(`${base}/books?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`);
  alert(txt);
  newTitle.value=''; newAuthor.value='';
  await refreshAll();
}


async function updStock(){
  const bookId=updBookId.value,stock=updStockValue.value;
  if(!bookId||stock===''){alert('请输入书籍ID和新库存');return;}
  const txt=await post(`${base}/books/updateStock/?book_id=${bookId}&new_stock=${stock}`);
  alert(txt);
  updBookId.value=''; updStock.value='';
  await refreshAll();
}


loadBooks();
</script>